import React, { Component } from 'react';
import { Text, View, Slider, TextInput } from 'react-native';
import _ from 'lodash';
import StatusIcon from '../../statusIcon';
import { parseErrors } from '../..';
import styles from '../styles';
import Editor from './editor';

export default class Number extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.initialValue || 0
    };
  }
  componentWillReceiveProps(next) {
    if (next.value !== this.props.value) {
      this.setState(
        {
          value: next.value
        },
        () => {
          if (_.isFunction(this.props.afterChange)) {
            this.props.afterChange(next.value);
          }
        }
      );
    }
  }
  onChange = value => {
    this.props.onChange(value);
  };
  onValueChange = (value) => {
    if (!_.isNumber(value)) {
      value = parseInt(value, 10);
    }
    if (!value) {
      value = 0;
    }
    if((this.props.maximumValue || this.props.maximumValue === 0) && value > this.props.maximumValue) {
      value = this.props.maximumValue
    }
    if((this.props.minimumValue || this.props.minimumValue === 0) && value < this.props.minimumValue) {
      value = this.props.minimumValue
    }
    this.setState({
      value
    });
  };
  render() {
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>
            {this.props.label}
          </Text>
        </View>
        <View style={styles.value}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
            <Slider
              step={this.props.step || 1}
              maximumValue={this.props.maximumValue}
              minimumValue={this.props.minimumValue}
              onSlidingComplete={this.onChange}
              onValueChange={this.onValueChange}
              value={this.state.value}
              style={{ flex: 1 }}
            />
            {this.props.showValue && !this.props.allowEdit ? (
              <Text>{this.state.value}</Text>
            ) : null}
            {this.props.allowEdit ? (
              <Editor
                value={this.state.value || '0'}
                onChange={this.onValueChange}
                maximumValue={this.props.maximumValue}
                minimumValue={this.props.minimumValue}
              />
            ) : null}
          </View>
        </View>
        {this.props.error ? (
          <StatusIcon type="error" msg={parseErrors(this.props.error)} />
        ) : null}
      </View>
    );
  }
}
